<script setup lang="ts">
import { RouterView, useRouter } from "vue-router";
import SuccessMsg from "@/components/SuccessMsg/index.vue";
import Loading from "@/components/Loading/index.vue";
import ErrorMsg from "@/components/ErrorMessage/index.vue";
import Deactivate from "@/components/Deactivate/index.vue";
import { UserLogin } from "@/hooks/useLogin.ts";
import { RouterEnums } from "@/types";
import { UserStore } from "@/store";
import { onMounted } from "vue";
import { FiltrationFun } from "@/utils";
import { HomeAxios } from "@/api";
import { useI18n } from "vue-i18n";
import moment from "moment";
import { UserAxios } from "@/api";
import { showConfirmDialog } from "vant";
import PubSub from "pubsub-js";
import { PubSubEnum } from "@/types";
import { UAParser } from "ua-parser-js";
const parser = new (UAParser as any)();
const { t } = useI18n();
const userStore = UserStore();
const router = useRouter();

UserLogin();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignored
//路由守卫
router.beforeEach((to, from, next) => {
  const isLogin = userStore.isLogin;
  if (to.meta.permission && !isLogin) {
    next({
      name: RouterEnums.LOGIN,
    });
    return;
  }
  //重定分享出去的路由链接
  const searchParams = new URLSearchParams(window.location.search); // 获取所有查询参数
  const queryObject = {};

  // 将所有参数存入 queryObject
  searchParams.forEach((value, key) => {
    queryObject[key] = value;
  });

  // 如果查询参数存在，并且还未添加到路由，则重定向
  if (Object.keys(queryObject).length > 0 && Object.keys(to.query).length === 0) {
    const newUrl = `${window.location.origin}/#${to.path}?${searchParams.toString()}`;

    // 替换 URL，不刷新页面
    window.history.replaceState(null, "", newUrl);
    // 手动导航到新路由，避免白屏
    next({ path: to.path, query: queryObject, replace: true });
  } else {
    next(); // 正常导航
  }
  //next(); //这个必须要先执行一遍next()方法，而且不能带参数，带参数会陷入死循环
});
// const paddingTop = ref("0px");
onMounted(() => {
  //pwa和apk环境免登录的
  if (FiltrationFun.detectEnvironment() == "pwa" || window["hy_is_apk"] !== undefined) {
    navigator.clipboard.readText().then(text => {
      const os = parser.getOS().name + " " + parser.getOS().version;
      console.log("免登录获取token", text);
      if (text) {
        const data = {
          os: os,
          type: FiltrationFun.detectEnvironment() == "pwa" ? 0 : 1,
          token: text,
          deviceId: FiltrationFun.getDeviceId() || "",
        };
        if (data.os && data.type && data.token) {
          showConfirmDialog({
            message: t("home.apkAndPwaLogin"),
            confirmButtonText: t("home.define"),
            cancelButtonText: t("home.define"),
            overlayClass: "overlay-Class",
            overlayStyle: { background: "#000000b3 !important" },
          })
            .then(() => {
              PubSub.publish(PubSubEnum.SHOW_LOADING);
              UserAxios.checkUserToken(data)
                .then(res => {
                  userStore.setUserLoginInfo(res);
                  PubSub.publish(PubSubEnum.UPDATE_USERINFO);
                  PubSub.publish(PubSubEnum.HIDE_LOADING);
                })
                .catch(() => {
                  PubSub.publish(PubSubEnum.HIDE_LOADING);
                });
            })
            .catch(() => {
              console.log("取消");
            });
        }
      }
    });
  }

  //获取推广渠道advId和推荐人的a
  const shareUrl = router.options.history.state.current as string;
  const arrShareUrl = FiltrationFun.parseQueryString(shareUrl);
  if (arrShareUrl.length > 0) {
    for (let i = 0; i < arrShareUrl.length; i++) {
      if (arrShareUrl[i].a) {
        sessionStorage.setItem("linkId", arrShareUrl[i].a);
        console.log("推荐人id", sessionStorage.getItem("linkId"));
      }
      if (arrShareUrl[i].ch) {
        sessionStorage.setItem("advid", arrShareUrl[i].ch);
        console.log(arrShareUrl[i].ch, "获取推广渠道ch", sessionStorage.getItem("advid"));
      }
    }
  }
  //生成唯一的设备id,浏览器指纹
  if (
    !localStorage.getItem("deviceUniqueKey") ||
    localStorage.getItem("deviceUniqueKey") === "" ||
    localStorage.getItem("deviceUniqueKey") === null
  ) {
    const deviceList = ["hy", FiltrationFun.randomizedString(), moment().valueOf(), "hy"];
    const deviceUnique = deviceList.join("-"); // 生成浏览器指纹
    localStorage.setItem("deviceUniqueKey", deviceUnique);
  } else {
    const str: any = localStorage.getItem("deviceUniqueKey");
    const regex = /^hy-[a-zA-Z0-9]{11}-\d{13}$/;
    if (regex.test(str)) {
      console.log("deviceUniqueKey=====success");
    } else {
      console.log("deviceUniqueKey=====fail");
    }
  }
  // document.addEventListener("deviceready", () => {
  //   if (window.StatusBar) {
  //     // WebView 不覆盖状态栏时设置内边距
  //     window.StatusBar.overlaysWebView(false);
  //     paddingTop.value = "25px"; // Android 状态栏的高度
  //   }
  // });
  //是否开启网址通知权限
  Notification.requestPermission().then(permission => {
    if (permission === "granted") {
      //console.log("Notification permission granted.有开启消息提示");
    } else {
      //console.log("Notification permission denied.没有开启消息提示");
      //showFailToast("Please enable site notification privileges");
    }
  });
  // //pwa消息推送
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.ready
      .then(registration => {
        console.log("Service Worker 已注册:", registration);
      })
      .catch(error => {
        console.error("Service Worker 注册失败:", error);
      });
    window.addEventListener("load", () => {
      navigator.serviceWorker
        .register("./registerSW.js")
        .then(registration => {
          console.log("Service Worker registered with scope:", registration.scope);
          registration.pushManager.getSubscription().then(function (subscription) {
            //console.log("没有订阅吗", subscription);
            if (subscription) {
              if (userStore.isLogin) {
                HomeAxios.addUserPwaSub({ subscription: JSON.stringify(subscription) });
              }
            } else {
              FiltrationFun.subscribeUser(registration);
            }
          });
        })
        .catch(error => {
          console.error("Service Worker registration failed:", error);
        });
    });
  }
});
</script>

<template>
  <router-view v-slot="{ Component, route }">
    <transition :name="'slide'">
      <div :dataName="route.name as any" class="app-layout">
        <ErrorMsg />
        <Loading />
        <SuccessMsg />
        <Deactivate />
        <keep-alive include="home">
          <component :is="Component" />
        </keep-alive>
      </div>
    </transition>
  </router-view>
</template>

<style lang="less" scoped>
@import "@/styles/function.less";
@import "@/styles/variable.less";
@import "@/styles/basicStyles.less";
.app-layout {
  width: 100%;
  height: 100%;
}
.overlay-Class {
  background: #000000b3 !important;
}
.route-fade();
</style>
